package com.LeetCode.List;

import org.junit.Test;

/**
 * 旋转链表
 */
public class rotateRight {
    public ListNode rotateRight(ListNode head, int k) {
        if(k == 0 || head == null || head.next == null) return head;

        ListNode pNode = head;
        int count = 1;
        while(pNode.next!=null){
            pNode = pNode.next;
            count++;
        }
        k %= count;
        if(k == 0) return head;

        //转化为循环链表
        pNode.next = head;

        for(int i = 0; i< count - k; i++){
            pNode = pNode.next;
        }
        ListNode newHead = pNode.next;
        pNode.next = null;
        return newHead;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode.printList(rotateRight(node1,2));
    }
}
